package com.example.crm_system.config;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.crm_system.entity.User;
import com.example.crm_system.exception.MyOwnException;
import com.example.crm_system.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

// JWT拦截器
@Component
public class JwtInterceptor implements HandlerInterceptor {

        private static final Logger log = LoggerFactory.getLogger(JwtInterceptor.class);

    @Resource
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        // 放行OPTIONS预检请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true; // 直接通过验证
        }

        // 从http请求的header中获取token
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            // 如果没找到，试试从参数里获取token
            token = request.getParameter("token");
        }

        if (token == null) {
            throw new MyOwnException("在请求标头中缺少token");
        }
        //认证
        if (StrUtil.isBlank(token)) {
            throw new MyOwnException("无token，请重新登录");
        }

        String userId;
        User user;
        try {
            // 解码token的载荷 -> userId
            userId = JWT.decode(token).getAudience().get(0);
            // 通过userId把数据库中的用户查询到
            user = userService.findById(Integer.parseInt(userId));
        } catch (Exception e) {
            String errMsg = "token验证失败，请重新登录";
            log.error(errMsg + ", token=" +  token, e);
            throw new  MyOwnException(errMsg);
        }
        if (user == null) {
            throw new  MyOwnException("用户不存在，请重新登录");
        }
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            throw new MyOwnException("token验证失败，请重新登录");
        }
        return true;
    }
}










